<template>
  <el-form ref="nodeEvent" :model="eventVal" label-width="200px">
    <el-form-item v-for="item in fliterEvents()" :key="item.value" :label="item.text">
      <el-select
        :key="ver"
        v-model="eventVal[item.value]"
        :disabled="readonly"
        :placeholder="item.text + '审批事件'"
        :clearable="true"
        @change="val=> saveEvent(item, val)"
      >
        <el-option v-for="t in getItems(item.value)" :key="t.Id" :label="t.InterName" :value="t.Id" />
      </el-select>
    </el-form-item>
  </el-form>
</template>

<script>
import { FlowEventList } from '@/flow/config/flowConfig'
import { Set } from '@/flow/api/flowNodeEvent'
import { GetItems } from '@/flow/api/flowInter'

export default {
  components: {
  },
  props: {
    nodeId: {
      type: String,
      default: null
    },
    flowId: {
      type: String,
      default: null
    },
    readonly: {
      type: Boolean,
      default: false
    },
    nodeEvent: {
      type: Object,
      default: null
    },
    filterEvent: {
      type: Function,
      default: null
    },
    isLoad: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      FlowEventList,
      eventVal: {},
      eventList: [],
      ver: 1
    }
  },
  watch: {
    isLoad: {
      handler(val) {
        if (val) {
          this.initNodeEvent()
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.inititems()
  },
  methods: {
    fliterEvents() {
      return FlowEventList.filter(c => this.filterEvent(c.value))
    },
    initNodeEvent() {
      const ev = this.nodeEvent ? Object.assign({}, this.nodeEvent) : {}
      this.FlowEventList.forEach(c => {
        // eslint-disable-next-line no-prototype-builtins
        if (!ev.hasOwnProperty(c.value)) {
          ev[c.value] = null
        }
      })
      this.eventVal = ev
    },
    async saveEvent(item, val) {
      const id = item.value
      await Set({
        FlowId: this.flowId,
        NodeId: this.nodeId,
        EventType: id,
        EventId: val
      })
      this.ver = this.ver + 1
      this.eventVal[id] = val
      this.$emit('update:nodeEvent', this.eventVal)
    },
    async inititems() {
      this.eventList = await GetItems()
    },
    getItems(range) {
      return this.eventList.filter(c => (range & c.UseRange) === range)
    }
  }
}
</script>
